<template>
  <div class="dashboard-container">
    <!-- 顶部标题栏 -->
    <header class="dashboard-header" style="background: #FFFFFF00;">
      <div class="title-group">
        <h1 class="main-title">北京市碳排放监测平台</h1>
        <h2 class="sub-title">基于卫星遥感数据的碳足迹分析</h2>
      </div>
      <div class="date-weather">
        <span class="current-date">{{ currentDate }}</span>
        <span class="weather-info">{{ weatherInfo }}</span>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="dashboard-content">

      <!-- 筛选条件区域 (1-1) -->
      <div class="filter-panel grid-cell cell-1-1">
        <div class="filter-item">
          <h3>年份选择</h3>
          <el-select v-model="selectedYears" multiple placeholder="请选择年份" style="width: 100%"
            :default-first-option=true>
            <el-option v-for="year in yearOptions" :key="year" :label="year" :value="year" />
          </el-select>
        </div>
        <div class="filter-item">
          <h3>行业领域</h3>
          <el-select v-model="selectedIndustry" placeholder="请选择行业" style="width: 100%" :default-first-option=true>
            <el-option v-for="inductry in industryOptions" :key="inductry.value" :label="inductry.label"
              :value="inductry" />
          </el-select>
        </div>
        <div class="filter-item">
          <h3>行政区域</h3>
          <el-select v-model="selectedDistrict" placeholder="请选择区域" class="district-select">
            <el-option v-for="district in districtOptions" :key="district" :label="district" :value="district" />
          </el-select>
        </div>
      </div>

      <!-- 图表展示区域 -->
      <!-- 行业占比饼图 (1-2) -->
      <div class="grid-cell cell-1-2 chart-container">
        <div class="chart-title"><span style="color:cyan">{{ selectedYears[0] }}</span> 北京市 碳排放行业占比</div>
        <div class="chart" ref="pieChart"></div>
      </div>

      <div class="grid-cell cell-1-3 chart-container">
        <!-- 柱状图折线图区域 -->
        <div class="chart-title"><span style="color:cyan">{{ selectedDistrict }}</span> 碳排放趋势</div>
        <div class="chart" ref="mutipleChart"></div>
      </div>

      <div class=" grid-cell cell-3-3 chart-container">
        <!-- 动态折线图区域 -->
        <div class="chart-title"><span style="color:cyan">{{ selectedDistrict }} {{ selectedIndustry.label }}</span> 行业碳排放趋势 {{ selectedYears.length <= 1 ? "" : " 对比" }}</div>
            <div class="chart" ref="compareChart"></div>
        </div>

        <!-- 热力图区域 (2-1 到 3-2) -->
        <div class="grid-cell cell-2-1 chart-container" style="background-color: #FFFFFF00;">
          <div class="chart-title">北京市碳排放热力图</div>
          <div class="chart" ref="heatMap"></div>
        </div>

        <!-- 区域排名 (4-1 和 4-2) -->
        <div class="grid-cell cell-4-1 chart-container">
          <div class="chart-title">区域碳排放排名</div>
          <div class="chart" ref="rankChart1"></div>
        </div>
    </main>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElCheckbox, ElCheckboxGroup, ElRadio, ElRadioGroup, ElSelect, ElOption, ElLoading } from 'element-plus'
import dataService from '../services/dataService'
import geoJson from '@/assets/beijing.json'
import { pa, te } from 'element-plus/es/locales.mjs'
import { formatter } from 'element-plus'

export default {
  name: 'Dashboard',
  components: {
    ElCheckbox,
    ElCheckboxGroup,
    ElRadio,
    ElRadioGroup,
    ElSelect,
    ElOption
  },
  setup() {
    const currentDate = ref('')
    const weatherInfo = ref('晴 25-33℃')

    // 每秒更新时间
    const updateCurrentTime = () => {
      currentDate.value = new Date().toLocaleString()
      setTimeout(updateCurrentTime, 1000)
    }
    updateCurrentTime()

    // 筛选条件数据
    const yearOptions = ref(['2019', '2020', '2021', '2022', '2023', '2024', '2025'])
    const selectedYears = ref(['2019'])

    const dimensionOptions = ref([
      { label: '月度数据', value: 'month' },
      { label: '每日数据', value: 'day' }
    ])
    const selectedDimension = ref('month')

    const industryOptions = ref([
      { label: '全部', value: 'total' },
      { label: '电力', value: 'power' },
      { label: '运输', value: 'transport' },
      { label: '航空', value: 'aerospace' },
      { label: '工业', value: 'industry' },
      { label: '消费', value: 'consume' },
    ])
    const selectedIndustry = ref({ label: '全部', value: 'total' })

    const districtOptions = ref(['全北京',
      '东城', '西城', '朝阳', '海淀',
      '丰台', '石景山', '门头沟', '房山',
      '通州', '顺义', '昌平', '大兴',
      '怀柔', '平谷', '密云', '延庆'
    ])
    const selectedDistrict = ref('全北京')

    // 图表引用
    const pieChart = ref(null)
    const lineChart1 = ref(null)
    const lineChart2 = ref(null)
    const lineChart3 = ref(null)
    const lineChart4 = ref(null)
    const heatMap = ref(null)
    const heatMapDetail = ref(null)
    const rankChart1 = ref(null)
    const rankChart2 = ref(null)
    const mutipleChart = ref(null)
    const compareChart = ref(null)


    // 注册北京市地图
    const registerBeijingMap = async () => {
      try {
        console.log('获取json 数据 start')
        // const geoJson2 = await import('@/assets/beijing.json')
        // console.log('获取json 数据 over' + geoJson.default)

        echarts.registerMap('beijing', geoJson)
      } catch (error) {
        console.error('加载北京地图数据失败:', error)
      }
      console.log('加载北京地图数据')

    }

    // 数据引用
    const industryRatio = ref([])
    const heatMapData = ref([])
    const districtRank = ref([])
    const industryTrend = ref({})
    const industryTrends = ref({})

    // 初始化数据
    const initData = async () => {
      try {
        const [
          ratioRes,
          heatMapRes,
          rankRes,
          trendRes,
          trendsRes
        ] = await Promise.all([
          dataService.readIndustryRatio(2019),
          dataService.readHeatMapData(2019, selectedIndustry.value.value),
          dataService.readDistrictRank(),
          dataService.readYearlyDistrictTrend(2019, selectedDistrict.value),
          dataService.getIndustryTrends(selectedYears.value, selectedDistrict.value, selectedIndustry.value.value)

        ])

        industryRatio.value = ratioRes.value
        heatMapData.value = heatMapRes.value
        districtRank.value = rankRes.value
        industryTrend.value = trendRes.value
        industryTrends.value = trendsRes.value

        // console.log(industryRatio.value);
        // console.log(heatMapData.value);
        // console.log(districtRank.value);
        // console.log(industryTrend.value);
        // console.log(industryTrends.value);


      } catch (error) {
        console.error('初始化数据失败:', error)
      }
    }

    // 获取天气数据(使用CORS代理)
    const fetchWeatherData = async () => {
      console.log('获取天气数据:')
      // try {
      //   // 使用公共CORS代理√
      //   const proxyUrl = 'https://cors-anywhere.herokuapp.com/'
      //   const apiUrl = 'http://t.weather.itboy.net/api/weather/city/101010100'

      //   const response = await fetch(proxyUrl + apiUrl, {
      //     headers: {
      //       'X-Requested-With': 'XMLHttpRequest'
      //     }
      //   })

      //   const data = await response.json()
      //   console.log('获取天气数据:', data)

      //   if (data.status === 200 && data.data) {
      //     const weather = data.data
      //     const temp = weather.wendu
      //     const condition = weather.forecast[0].type
      //     weatherInfo.value = `${condition} ${temp}℃`
      //   } else {
      //     weatherInfo.value = '天气数据获取失败'
      //   }
      // } catch (error) {
      //   console.error('获取天气数据失败:', error)
      //   weatherInfo.value = '天气数据获取失败'
      // }
    }

    // 定时刷新数据
    const startDataRefresh = () => {
      setInterval(() => {
        fetchWeatherData()
        updateChartsData()
      }, 30000) // 每30秒刷新一次
    }

    onMounted(async () => {
      fetchWeatherData()
      await initData()

      registerBeijingMap()
      initPieChart()
      initHeatMap()
      initMutipleLineChart()
      initCompareCharts()
      initRankCharts()
    })

    const initPieChart = () => {
      const chart = echarts.init(pieChart.value)
      // console.log(pieChart.value);
      const option = {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            // console.log(params);
            var res = params.seriesName + '<br/>';
            res += params.marker + params.name + ' : ' + params.value.toFixed(2);
            return res;
          }
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          textStyle: {
            color: '#8f9ba8'
          }
        },
        series: [{
          name: '碳排放占比',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#0f1621',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: '{b}: {c} ({d}%)',
            color: '#fff'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: true
          },
          data: industryRatio.value || []
        }]
      }
      chart.setOption(option)

      //性能优化：在非激活窗口时暂停动画
      let hidden = false
      const visibilityChange = () => {
        if (document.hidden) {
          chart.dispatchAction({ type: 'hideTip' })
          hidden = true
        } else if (hidden) {
          chart.dispatchAction({ type: 'showTip' })
          hidden = false
        }
      }
      document.addEventListener('visibilitychange', visibilityChange)

      onUnmounted(() => {
        document.removeEventListener('visibilitychange', visibilityChange)
        window.removeEventListener('resize', handleResize)
      })
    }

    const initHeatMap = () => {
      const chart = echarts.init(heatMap.value)
      // console.log(heatMapData.value);
      let max = 0;
      heatMapData.value.forEach(item => {
        if (max < item.value && item.name !== 'CO2') {
          max = item.value;
        }
      })
      console.log("max in heatMapData : ", max);

      const option = {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: params => {
            return `${params.name}<br/>碳排放量: ${params.value.toFixed(2)}`
          }
        },
        visualMap: {
          min: 0,
          max: max,
          text: ['高', '低'],
          realtime: false,
          calculable: true,
          inRange: {
            color: ['#50a3ba', '#eac736', '#d94e5d']
          },
          // textStyle: {
          //   color: '#fff'
          // },
          left: 'right',
          top: 'bottom',
          // dimension: 1,
          // seriesIndex: 0
        },
        dataZoom: [
          {
            type: 'inside', // 或者 'inside'

            start: 50, // 最小显示的数据比例，这里是数据的50%
            end: 100 // 最大显示的数据比例，这里是数据的100%
          }
        ],
        series: [
          {
            type: 'map',
            map: 'beijing',
            geoIndex: 0,
            roam: true,
            data: heatMapData.value || [],
            label: {
              show: true,
              color: '#fff'
            },
            itemStyle: {
              areaColor: '#f5f5f5',
              borderColor: '#ccc'
            }
          }
        ]
      }
      chart.setOption(option)

      // 热力图点击事件
      chart.on('click', params => {
        // updateHeatMapDetail(params.name)
      })
    }

    const updateHeatMapDetail = (districtName) => {
      const chart = echarts.init(heatMapDetail.value)
      const districtData = industryRatio.find(item => item.name === districtName)
      // console.log("districtData : ");
      // console.log(districtData);
      const option = {
        backgroundColor: 'transparent',
        title: {
          text: `${districtName}碳排放详情`,
          left: 'center',
          textStyle: {
            color: '#fff',
            fontSize: 14
          }
        },
        tooltip: {
          trigger: 'item'
        },
        series: [{
          name: '碳排放',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#0f1621',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: '{b}: {c} ({d}%)',
            color: '#fff'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '14',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: true
          },
          data: [
            { value: districtData.value * 0.45, name: '电力' },
            { value: districtData.value * 0.25, name: '运输' },
            { value: districtData.value * 0.15, name: '航天' },
            { value: districtData.value * 0.15, name: '工业' }
          ]
        }]
      }
      chart.setOption(option)
    }

    const initMutipleLineChart = () => {
      const chart = echarts.init(mutipleChart.value)

      var legendDatas = [];
      var series = [];

      var totalYearly = industryTrend.value.map(item => item.total);
      // console.log("totalYearly : ");
      // console.log(totalYearly);
      industryOptions.value.forEach((item, index) => {
        legendDatas.push(item.label);
        const key = item.value;
        if (key !== "total") {
          const domainData = {
            name: item.label,
            type: 'bar',
            data: industryTrend.value.map(item => item[key]),
          };
          series.push(domainData);
        }
      })

      const totalData = {
        name: '全部',
        type: 'line',
        data: totalYearly,
        color: "#FFD602"
      }
      series.push(totalData);

      const colors = ['#3ED164', '#91CC75', '#EE6666', "#9A60B4", '#FF9F7F', '#00D2FF'];
      var option = {
        color: colors,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          formatter: function (params) {
            // console.log(params);
            var res = '';
            params.forEach((item,index) => {
              if (index == 0) {
                res += item.axisValue + '<br/>';
              }
              res += item.marker + item.seriesName + ' : ' + item.value.toFixed(2);
              if (index < params.length - 1) {
                res += '<br/>';
              }
            });
            return res;
          }
        },

        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        legend: {
          data: legendDatas,
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: [
          { 
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            // prettier-ignore
            data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: 'CO₂排放量( CO₂e)',
            position: 'left',
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: "#4DB9F4"
              }
            },
            axisLabel: {
              formatter: function (value) {
                return value.toFixed(2);
              }
            }
          }
        ],
        series: series
      };

      chart.setOption(option)
    }

    const initCompareCharts = () => {
      console.log("initCompareChart");
      const chart = echarts.init(compareChart.value)
      var legendDatas = [];
      var series = [];
      var induskeys = selectedIndustry.value.value

      selectedYears.value.forEach((item, index) => {

        legendDatas.push(item);
        const key = item;
        // console.log("selectedYears " + item);
        // console.log("key " + key);
        // console.log(industryTrends.value);
        // console.log(industryTrends.value[key]);
        // console.log("induskeys " + induskeys);

        if (industryTrends.value[key] !== undefined) {
          const linedata = industryTrends.value[key].map((item, index) => {
            return item[induskeys]
          });
          // console.log(item);

          const domainData = {
            name: item,
            type: 'line',
            data: linedata
          };
          series.push(domainData);
        }
      })


      const colors = ['#91CC75', '#EE6666', "#9A60B4", '#FF9F7F', '#00D2FF', '#3ED164'];
      var option = {
        color: colors,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          formatter: function (params) {
            // console.log(params);
            var res = '';
            params.forEach((item,index) => {
              if (index == 0) {
                res += item.axisValue + '<br/>';
              }
              res += item.marker + item.seriesName + ' : ' + item.value.toFixed(2);
              if (index < params.length - 1) {
                res += '<br/>';
              }
            });
            return res;
          }
        },

        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        legend: {
          data: legendDatas,
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: [
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            // prettier-ignore
            data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: 'CO₂排放量( CO₂e)',
            position: 'left',
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: "#4DB9F4"
              }
            },
            axisLabel: {
              formatter: function (value) {
                return value.toFixed(2);
              }
            }
          }
        ],
        series: series
      };

      chart.setOption(option)


    }
    const initLineCharts = () => {
      // 销毁之前的图表实例
      chartRefs.value.forEach(chart => {
        if (chart && chart._echarts_instance_) {
          echarts.getInstanceByDom(chart)?.dispose()
        }
      })

      // // 根据选中的行业初始化图表
      // selectedIndustries.value.forEach((industry, index) => {
      //   const chartEl = chartRefs.value[index]
      //   if (chartEl) {
      //     const chart = echarts.init(chartEl)
      //     const trendData = industryTrend[industry] || []
      //     const label = getIndustryLabel(industry)
      //     chart.setOption(getLineOption(label, trendData))
      //   }
      // })
    }

    const getLineOption = (name, data) => {

      // console.log(data);
      return {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
          axisLine: {
            lineStyle: {
              color: '#8f9ba8'
            }
          },
          axisLabel: {
            color: '#8f9ba8'
          }
        },
        yAxis: {
          type: 'value',
          name: '碳排放量',
          nameTextStyle: {
            color: '#8f9ba8'
          },
          axisLine: {
            lineStyle: {
              color: '#8f9ba8'
            }
          },
          axisLabel: {
            color: '#8f9ba8',
            formatter: function (value) {
                return value.toFixed(2);
              }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(143, 155, 168, 0.2)'
            }
          }
        },
        series: [{
          name: name,
          type: 'line',
          smooth: true,
          data: data,
          itemStyle: {
            color: '#3a7bd5'
          }
          ,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(58, 123, 213, 0.5)'
              },
              {
                offset: 1,
                color: 'rgba(58, 123, 213, 0.1)'
              }
            ])
          }
        }]
      }
    }

    const initRankCharts = () => {
      // 区域排名柱状图
      const rank = echarts.init(rankChart1.value)
      rank.setOption(getBarOption('区域碳排放排名', districtRank.value))
    }

    const getBarOption = (title, data) => {



      return {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: params => {
            // console.log(params);
            const item = params[0]
            if (item !== undefined && item.value !== null) {
              return `${item.marker} ${item.name}<br/>碳排放量: ${item.value.toFixed(2)}`
            } else {
              return ''
            }
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#8f9ba8'
            }
          },
          axisLabel: {
            color: '#8f9ba8',
            formatter : function (value) {
              // console.log(value);
                return value.toFixed(2);
              }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(143, 155, 168, 0.2)'
            }
          }
        },
        yAxis: {
          type: 'category',
          data: data.map(item => item.name),
          axisLine: {
            lineStyle: {
              color: '#8f9ba8'
            }
          },
          axisLabel: {
            color: '#8f9ba8',
          }
        },
        series: [{
          name: title,
          type: 'bar',
          data: data.map(item => item.value),
          itemStyle: {
            color: params => {
              const colorList = ['#3ED164', '#91CC75', '#EE6666', "#9A60B4", '#FF9F7F', '#00D2FF']
              return colorList[params.dataIndex % colorList.length]
            }
          },
          label: {
            show: true,
            position: 'right',
            color: '#fff',
            formatter : function (params) {
              // console.log(params)
              const item = params
              if (item !== undefined && item.value !== null) {
                return `${item.value.toFixed(2)}`
              } else {
                return ''
              }
             }
          }
        }]
      }
    }

    // 窗口大小变化时重新调整图表大小
    const handleResize = () => {
      const charts = [
        pieChart.value, lineChart1.value, lineChart2.value,
        lineChart3.value, lineChart4.value, heatMap.value,
        heatMapDetail.value, rankChart1.value, rankChart2.value
      ]
      charts.forEach(chart => {
        if (chart) {
          echarts.getInstanceByDom(chart)?.resize()
        }
      })
    }

    onMounted(() => {
      // 添加加载动画
      const loading = ElLoading.service({
        lock: true,
        text: '数据加载中...',
        background: 'rgba(15, 22, 33, 0.8)',
        spinner: 'el-icon-loading'
      })

      // 模拟数据加载
      setTimeout(() => {
        // fetchWeatherData()
        // initPieChart()
        // initHeatMap()
        // initLineCharts()
        // initRankCharts()
        window.addEventListener('resize', handleResize)
        // startDataRefresh()
        loading.close()
      }, 1000)
    })

    onUnmounted(() => {
      window.removeEventListener('resize', handleResize)
    })

    // 导出数据为图片
    const exportAsImage = (chartRef) => {
      const chartInstance = echarts.getInstanceByDom(chartRef.value)
      if (chartInstance) {
        const img = new Image()
        img.src = chartInstance.getDataURL({
          type: 'png',
          pixelRatio: 2,
          backgroundColor: '#0f1621'
        })
        const win = window.open('', '_blank')
        win.document.write(img.outerHTML)
      }
    }



    // 监听选中的行业变化
    watch(selectedIndustry, (newVal) => {
      nextTick(() => {
        console.log('选中的行业：', newVal)
        console.log('选中的 年：', selectedYears.value[0])

        dataService.getIndustryTrends(selectedYears.value, selectedDistrict.value, newVal.value)
          .then(result => {
            industryTrends.value = result.value
            console.log('industryTrend changed')
            initCompareCharts()

          })
          .catch(error => {
            console.error('获取行业趋势数据失败:', error)
          })

        if (selectedYears.value.length !== 0) {
          dataService.readHeatMapData(selectedYears.value[0], newVal.value)
            .then(result => {
              heatMapData.value = result.value
              console.log('heatMapData changed')
              initHeatMap()
            })
            .catch(error => {
              console.error('获取热力图数据失败:', error)
            })
        }
      })
    }, { deep: true })

    watch(selectedYears, (newVal) => {
      nextTick(() => {
        console.log('选中的时间：', newVal)

        dataService.readHeatMapData(newVal[0], selectedIndustry.value.value)
          .then(result => {
            heatMapData.value = result.value
            console.log('heatMapData changed')
            initHeatMap()
          })
          .catch(error => {
            console.error('获取热力图数据失败:', error)
          })

        dataService.readIndustryRatio(newVal[0])
          .then(result => {
            industryRatio.value = result.value
            console.log('industryRatio changed')
            initPieChart()
          })
          .catch(error => {
            console.error('获取行业占比数据失败:', error)
          })

        dataService.readYearlyDistrictTrend(newVal[0], selectedDistrict.value)
          .then(result => {
            industryTrend.value = result.value
            console.log('industryTrend changed')
            console.log(newVal)
            initMutipleLineChart()
          })
          .catch(error => {
            console.error('获取年度趋势数据失败:', error)
          })
        dataService.getIndustryTrends(newVal, selectedDistrict.value, selectedIndustry.value)
          .then(result => {
            industryTrends.value = result.value
            console.log('industryTrend changed')
            initCompareCharts()

          })
          .catch(error => {
            console.error('获取多年度趋势数据失败:', error)
          })
      })
    }, { deep: true })

    watch(selectedDistrict, (newVal) => {
      nextTick(() => {
        console.log('选中的区域：', newVal)
        dataService.readYearlyDistrictTrend(selectedYears.value[0], newVal)
          .then(result => {
            industryTrend.value = result.value
            console.log('industryTrend changed')
            console.log(industryTrend.value)
            initMutipleLineChart()
          })
          .catch(error => {
            console.error('获取区域趋势数据失败:', error)
          })
        dataService.getIndustryTrends(selectedYears.value, newVal, selectedIndustry.value)
          .then(result => {
            industryTrends.value = result.value
            console.log('industryTrend changed')
            initCompareCharts()

          })
          .catch(error => {
            console.error('获取多年度趋势数据失败:', error)
          })
      })
    }, { deep: true })


    // 动态图表引用
    const chartRefs = ref([])
    const setChartRef = (el, index) => {
      if (el) {
        chartRefs.value[index] = el
      }
    }

    // 获取行业标签
    const getIndustryLabel = (value) => {
      const industry = industryOptions.value.find(item => item.value === value)
      return industry ? industry.label : value
    }
    // 更新图表数据
    const updateChartsData = () => {
      // 模拟根据筛选条件获取新数据
      // const newData = {
      //   industryRatio: [
      //     { value: 45 * Math.random(), name: '电力' },
      //     { value: 25 * Math.random(), name: '运输' },
      //     { value: 15 * Math.random(), name: '航天' },
      //     { value: 15 * Math.random(), name: '工业' }
      //   ],
      //   heatMapData: heatMapData.map(item => ({
      //     ...item,
      //     value: Math.floor(Math.random() * 100)
      //   })),
      //   districtRank: districtRank.map(item => ({
      //     ...item,
      //     value: Math.floor(Math.random() * 150)
      //   }))
      // }

      // // 更新饼图
      // const pieChartInstance = echarts.getInstanceByDom(pieChart.value)
      // pieChartInstance.setOption({
      //   series: [{
      //     data: newData.industryRatio
      //   }]
      // })
      // // 更新热力图
      // const heatMapInstance = echarts.getInstanceByDom(heatMap.value)
      // heatMapInstance.setOption({
      //   series: [{
      //     data: newData.heatMapData
      //   }]
      // })

      // // 更新排名图
      // const rankChart1Instance = echarts.getInstanceByDom(rankChart1.value)
      // rankChart1Instance.setOption({
      //   yAxis: {
      //     data: newData.districtRank.map(item => item.name)
      //   },
      //   series: [{
      //     data: newData.districtRank.map(item => item.value)
      //   }]
      // })

      // const rankChart2Instance = echarts.getInstanceByDom(rankChart2.value)
      // rankChart2Instance.setOption({
      //   yAxis: {
      //     data: newData.districtRank.map(item => item.name)
      //   },
      //   series: [{
      //     data: newData.districtRank.map(item => item.value)
      //   }]
      // })
    }

    return {
      currentDate,
      weatherInfo,
      yearOptions,
      selectedYears,
      dimensionOptions,
      selectedDimension,
      industryOptions,
      selectedIndustry,
      districtOptions,
      selectedDistrict,
      pieChart,
      mutipleChart,
      compareChart,
      heatMap,
      heatMapDetail,
      rankChart1,
      rankChart2,
      exportAsImage,
      chartRefs,
      setChartRef,
      getIndustryLabel,
      // 添加筛选变化监听
      watch: {
        selectedYears() {
          console.log('selectedYears changed')
          updateChartsData()
        },
        selectedDimension() {
          console.log('selectedDimension changed')
          updateChartsData()
        },
        selectedIndustry() {
          console.log('selectedIndustry changed')
          updateChartsData()
        },
        selectedDistrict() {
          console.log('selectedDistrict changed')
          updateChartsData()
        }
      }
    }
  }
}
</script>

<style>
.dashboard-container {
  width: 100vw;
  /* 使用视窗宽度 */
  height: 100vh;
  overflow: hidden;
  /* 只在内容区滚动 */
  background-color: #0f1621;
  color: #fff;
  font-family: 'Arial', sans-serif;
  display: grid;
  grid-template-rows: 100px 1fr;
  position: relative;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .dashboard-container {
    grid-template-rows: 80px 1fr;
    overflow-y: auto;
  }

  .dashboard-header {
    padding: 0 15px;
    flex-direction: column;
    align-items: flex-start;
    height: auto;
    padding-bottom: 10px;
  }

  .title-group {
    margin-bottom: 5px;
  }

  .date-weather {
    flex-direction: row;
    align-items: center;
    gap: 10px;
  }

  .dashboard-content {
    grid-template-columns: 1fr;
    grid-template-rows: auto;
    gap: 8px;
    padding: 8px;
    height: auto;
  }

  .grid-cell {
    min-height: 300px;
  }

  /* 调整特殊单元格位置 */
  .cell-1-1 {
    grid-area: auto;
  }

  .cell-1-2 {
    grid-area: auto;
  }

  .cell-1-3 {
    grid-area: auto;
  }

  .cell-2-1 {
    grid-area: auto;
  }

  .cell-2-3 {
    grid-area: auto;
  }

  .cell-3-1 {
    grid-area: auto;
  }

  .cell-3-3 {
    grid-area: auto;
  }

  .cell-4-1 {
    grid-area: auto;
  }

  .cell-4-2 {
    grid-area: auto;
  }

  .cell-4-3 {
    grid-area: auto;
  }
}

/* 趋势图水平排列容器 */
.trend-charts-container {
  display: flex;
  flex-direction: row;
  gap: 10px;
  width: 100%;
  margin-bottom: 10px;
}

.trend-chart {
  flex: 1;
  /* 每个子项等宽 */
  min-width: 0;
  /* 防止溢出，建议加上 */
  max-width: 25%;
  /* 最多占据1/4宽度 */
  background: rgba(16, 31, 48, 0.7);
  border-radius: 8px;
  border: 1px solid rgba(58, 123, 213, 0.3);
  box-shadow: 0 0 15px rgba(58, 123, 213, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transition: all 0.3s ease;
  backdrop-filter: blur(5px);
}

/* 科幻风格背景效果 */
.dashboard-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
    radial-gradient(circle at 20% 30%, rgba(58, 123, 213, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 70%, rgba(0, 210, 255, 0.1) 0%, transparent 50%);
  pointer-events: none;
  z-index: 0;
}

.dashboard-container::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image:
    linear-gradient(rgba(58, 123, 213, 0.1) 1px, transparent 1px),
    linear-gradient(90deg, rgba(58, 123, 213, 0.1) 1px, transparent 1px);
  background-size: 50px 50px;
  pointer-events: none;
  z-index: 0;
}

.dashboard-header,
.dashboard-content,
.grid-cell {
  position: relative;
  z-index: 1;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  background: linear-gradient(90deg, #0a0e17 0%, #1a2a3a 100%);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5);
  z-index: 10;
}

.title-group {
  text-align: left;
}

.main-title {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  background: linear-gradient(90deg, #3a7bd5 0%, #00d2ff 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.sub-title {
  margin: 5px 0 0;
  font-size: 14px;
  color: #8f9ba8;
}

.date-weather {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.current-date {
  margin: 2px 0;
  font-size: 16px;
  font-weight: bold;
}

.weather-info {
  margin: 2px 0;
  font-size: 14px;
}

.dashboard-content {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  grid-template-rows: repeat(3, minmax(0, 1fr));
  gap: 10px;
  padding: 10px;
  width: 100%;
  min-width: 1600px;
  height: calc(100vh - 100px);
  box-sizing: border-box;
  overflow-x: auto;
}

.grid-cell {
  background: rgba(16, 31, 48, 0.7);
  border-radius: 8px;
  border: 1px solid rgba(58, 123, 213, 0.3);
  box-shadow: 0 0 15px rgba(58, 123, 213, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transition: all 0.3s ease;
  backdrop-filter: blur(5px);
}

/* .grid-cell:hover {
  box-shadow: 0 0 20px rgba(58, 123, 213, 0.3);
  transform: translateY(-2px);
  border-color: rgba(0, 210, 255, 0.5);
} */

/* 科幻风格动画效果 */
@keyframes sci-fi-glow {
  0% {
    box-shadow: 0 0 5px rgba(58, 123, 213, 0.3);
  }

  50% {
    box-shadow: 0 0 20px rgba(0, 210, 255, 0.5);
  }

  100% {
    box-shadow: 0 0 5px rgba(58, 123, 213, 0.3);
  }
}

/* .grid-cell:hover::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 8px;
  background: linear-gradient(
    135deg,
    rgba(58, 123, 213, 0.1) 0%,
    rgba(0, 210, 255, 0.1) 50%,
    rgba(58, 123, 213, 0.1) 100%
  );
  animation: sci-fi-glow 3s infinite;
  pointer-events: none;
  z-index: -1;
} */

.chart-container {
  position: relative;
}

.chart-title {
  padding: 10px;
  font-size: 14px;
  font-weight: bold;
  color: #3a7bd5;
  border-bottom: 1px solid rgba(58, 123, 213, 0.2);
}

.chart {
  flex: 1;
  width: 100%;
}

.filter-panel {
  display: grid;
  grid-template-rows: repeat(4, 1fr);
  gap: 10px;
  padding: 10px;
}

.filter-item {
  display: flex;
  align-items: center;
  background: rgba(26, 42, 58, 0.5);
  border-radius: 4px;
  padding: 8px;
}

.filter-item h3 {
  /* margin: 0 0 8px 0; */
  width: 70px;
  font-size: 12px;
  color: #8f9ba8;
}

.filter-checkbox {
  margin-right: 8px;
  margin-bottom: 5px;
}

.filter-radio {
  margin-right: 8px;
}

.district-select {
  width: 100%;
}

/* :deep(.el-checkbox__label),
:deep(.el-radio__label) {
  color: #8f9ba8;
  font-size: 12px;
}

:deep(.el-checkbox__inner),
:deep(.el-radio__inner) {
  background-color: rgba(16, 31, 48, 0.7);
  border-color: #3a7bd5;
} */

/* :deep(.el-select) {
  --el-select-input-focus-border-color: #3a7bd5;
}

:deep(.el-select-dropdown) {
  background-color: #0f1621;
  border: 1px solid #3a7bd5;
}

:deep(.el-select-dropdown__item) {
  color: #8f9ba8;
}

:deep(.el-select-dropdown__item.hover) {
  background-color: rgba(58, 123, 213, 0.2);
} */

/* 旋转90度后的布局 */
.cell-1-1 {
  grid-area: 1 / 1 / 2 / 2;
}

/* 筛选条件区域 */
.cell-1-2 {
  grid-area: 2 / 1 / 3 / 2;
}

/* 北京市碳排放行业占比饼状图 */
.cell-1-3 {
  grid-area: 3 / 1 / 4 / 3;
}

/* 电力行业趋势 */
.cell-2-1 {
  grid-area: 1 / 2 / 3 / 4;
}

/* 地图 - 合并2-1,2-2,3-1,3-2 */
.cell-2-3 {
  grid-area: 3 / 2 / 4 / 3;
}

/* 运输行业趋势 */
.cell-3-3 {
  grid-area: 3 / 3 / 4 / 5;
}

/* 航天行业趋势 */
.cell-4-1 {
  grid-area: 1 / 4 / 3 / 5;
}

/* 区域碳排放排名柱状图 - 合并4-1,4-2 */
.cell-4-3 {
  grid-area: 3 / 4 / 4 / 4;
}

/* 工业行业趋势 */
</style>